﻿using HardcoreGame.Content.Items.Consumables.Drinks.Waters;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;

namespace HardcoreGame.Common.Players
{
    public class RainwaterCollectionPlayer : ModPlayer
    {
        public int rainCollectionTimer = 0;
        public int holdCupTimer = 0;
        public bool isCollectingRain = false;
        public override void PostUpdate()
        {
            bool canCollectRain = Main.raining && !Player.ZoneSnow &&
                                  Player.HeldItem.type == ItemID.Mug &&
                                  IsAboveClear();
            if (canCollectRain)
            {
                if (!isCollectingRain)
                {
                    isCollectingRain = true;
                    rainCollectionTimer = 0;
                    holdCupTimer = 0;
                }
                holdCupTimer++;
                float rainIntensity = (float)Main.rainTime / Main.maxRaining;
                int collectionSpeed = (int)(600 * (1 - rainIntensity) + 60 * rainIntensity);
                rainCollectionTimer++;
                if (holdCupTimer >= 600 && rainCollectionTimer >= collectionSpeed)
                {
                    int newItemType = ModContent.ItemType<RainwaterMug>();
                    if (Player.ZoneCorrupt)
                    {
                        newItemType = ModContent.ItemType<CorruptRainwaterMug>();
                    }
                    else if (Player.ZoneCrimson)
                    {
                        newItemType = ModContent.ItemType<CrimsonRainwaterMug>();
                    }
                    else if (Player.ZoneHallow)
                    {
                        newItemType = ModContent.ItemType<HallowRainwaterMug>();
                    }
                    Player.HeldItem.TurnToAir();
                    Item.NewItem(Player.GetSource_ItemUse(Player.HeldItem), Player.position, newItemType);
                    isCollectingRain = false;
                    rainCollectionTimer = 0;
                    holdCupTimer = 0;
                }
            }
            else
            {
                isCollectingRain = false;
                rainCollectionTimer = 0;
                holdCupTimer = 0;
            }
        }
        private bool IsAboveClear()
        {
            int playerX = (int)(Player.position.X / 16);
            int playerY = (int)(Player.position.Y / 16);
            for (int y = playerY - 1; y >= 0; y--)
            {
                Tile tile = Main.tile[playerX, y];
                if (tile.HasTile)
                {
                    return false;
                }
            }
            return true;
        }
    }
}